package bookManage;

import java.util.Random;

/**
 * 书
 * 
 * @author 伟❤志
 *
 */
public class BookModel implements Comparable<BookModel> {

	private int id;// 书的编号--不能重复
	private String name;// 书名
	private int recordNum;// 借阅次数

	public int getId() {
		return id;
	}

	public void setId(int id) {
		// 判断是否存在这个id
		for (BookModel bookModel : Book.books) {
			if (bookModel.getId() == id) {// 找到相同id
				Random random = new Random();
				System.out.println("重复id！已为您自动生成新的id！");
				int newId = random.nextInt(2000000000) + 0;
				this.id = newId;
				return;
			}
		}
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getRecordNum() {
		return recordNum;
	}

	public void setRecordNum() {
		this.recordNum += 1;
	}

	public void setRecordNum(int recordNum) {
		this.recordNum = recordNum;
	}

	@Override
	public int compareTo(BookModel o) {
		int num = o.recordNum - this.recordNum;// 设置按借阅次数降序排列

		int num2 = num == 0 ? this.name.compareTo(o.name) : num;// 借阅次数和图书名都一致算同一种书

		return num2;
	}

	/**
	 * 查询全部图书
	 */
	public void selectAll() {
		for (BookModel book : Book.books) {
			bookInfo(book);
		}
	}

	/**
	 * 根据图书id找图书
	 * 
	 * @param id
	 * @return
	 */
	public BookModel selectById(int id) {
		for (BookModel book : Book.books) {
			if (book.getId() == id) {
				return book;
			}
		}
		return null;
	}

	/**
	 * 图书详细信息
	 * 
	 * @param book
	 */
	public void bookInfo(BookModel book) {
		System.out.println("-----------------------");
		System.out.println("图书编号：" + book.getId());
		System.out.println("书名:" + book.getName());
		System.out.println("借阅次数：" + book.getRecordNum());
		System.out.println("-----------------------");
		System.out.println();
	}

	/**
	 * 根据图书名查询图书信息
	 * 
	 * @param name
	 */
	public void selectByName(String name) {
		for (BookModel book : Book.books) {
			if (name.equals(book.getName())) {
				bookInfo(book);
			}
		}
	}

	/**
	 * 添加图书
	 * 
	 * 不能人为添加借阅数量
	 * 
	 * @param id
	 * @param name
	 */
	public void addBook(int id, String name) {

		BookModel bookModel = new BookModel();
		bookModel.setId(id);
		bookModel.setName(name);

		Book.books.add(bookModel);

		selectByName(name);
	}

	/**
	 * 修改图书信息
	 * 
	 * 借阅次数不能改
	 * 
	 * @param oName
	 * @param name
	 * @param id
	 */
	public void updateBook(String oName, String name, int id) {
		for (BookModel book : Book.books) {
			if (oName.equals(book.getName())) {
				book.setId(id);
				book.setName(name);
			}
		}
		selectAll();
	}
}
